package com.example.securitydemos.controller;

import com.example.securitydemos.bean.User;
import com.example.securitydemos.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @author linjy on 2023/1/31
 */
@RestController
public class UserController {

    //@Autowired
    //private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMapper userMapper;

    @Secured({"ROLE_ADMIN","ROLE_USER"})
    @GetMapping("/user/hello")
    public String helloUser() {

        return "hello, user";
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin/hello")
    public String helloAdmin() {

        return "hello, admin";
    }

    @PreAuthorize("#age>100")
    @GetMapping("/age")
    public String getAge(@RequestParam("age") Integer age) {

        return String.valueOf(age);
    }

    @GetMapping("/app/hello")
    public String helloApp() {

        return "hello, app";
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session) {
        session.invalidate();
        System.out.println("logout执行了...");
    }

    //定义一个会话过期后要跳转到的接口
    @GetMapping("/session/invalid")
    public String invalid() {

        return "会话过期invalid...";
    }


    /**
     * 添加用户.这里我们采用表单形式传参,传参形式如下:
     * http://localhost:8080/user/register?username=test&password=123
     */
    /*@GetMapping("/user/register")
    public User registerUser(User user){
        user.setEnable(true);
        user.setRoles("ROLE_ADMIN");

        //对密码进行加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        userMapper.addUser(user);

        return user;
    }*/


}
